package cn.electronic.sale.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sun.org.apache.bcel.internal.generic.NEW;

import cn.electronic.sale.pojo.Goods;
import cn.electronic.sale.pojo.GoodsCustom;
import cn.electronic.sale.pojo.GoodsQueryVo;
import cn.electronic.sale.pojo.GoodsUpload;

import sun.net.www.content.audio.basic;

/**
 * 类描述：商品控制类
 * 
 * @author: 陈明俊
 * @date： 日期：2016-12-14 时间：下午2:16:49
 * @version 1.0
 */
@Controller
@RequestMapping("/goods")
public class GoodsController extends BasicController {
	/**
	 * 商品搜索页
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findAllGoods")
	public String searchGood(HttpSession session, GoodsQueryVo goodsQueryVo)
			throws Exception {
		System.out.println(goodsQueryVo);
		List<Goods> goodsList = goodsService
				.selectGoodsByCondition(goodsQueryVo);
		List<GoodsCustom> goodsCustomsList = new ArrayList<GoodsCustom>();
		for (Goods goods : goodsList) {
			goodsCustomsList.add(goodsService
					.selectAllGoodsInfoByPrimaryKey(goods.getGoodsId()));
		}
		GoodsCustom goodsCustomSearch1 = null;
		GoodsCustom goodsCustomSearch2 = null;
		GoodsCustom goodsCustomSearch3 = null;
		GoodsCustom goodsCustomSearch4 = null;
		int j = 0;
		for (GoodsCustom goodsCustom : goodsCustomsList) {
			if (j == 0) {
				goodsCustomSearch1 = goodsCustom;
				
			}
			if (j == 1) {
				goodsCustomSearch2 = goodsCustom;
				
			}
			if (j == 2) {
				goodsCustomSearch3 = goodsCustom;
				
			}
			if (j == 3) {
				goodsCustomSearch4 = goodsCustom;
				
			}
			j++;
		}

		/*
		 * 本周热卖和每日推荐
		 */
		List<GoodsCustom> goodsCustomWeekHot4 = new ArrayList<GoodsCustom>();
		List<GoodsCustom> goodsCustomWeekHot3 = new ArrayList<GoodsCustom>();
		List<GoodsCustom> goodsCustoms = goodsService.selectAllGoodsInfo();
		int i = 0;
		for (GoodsCustom goodsCustom : goodsCustoms) {
			if (i++ == 7) {
				break;
			}
			if (i < 4) {
				goodsCustomWeekHot3.add(goodsCustom);
			} else {

				goodsCustomWeekHot4.add(goodsCustom);
			}
		}
		session.setAttribute("goodsCustomWeekHot4", goodsCustomWeekHot4);
		session.setAttribute("goodsCustomWeekHot3", goodsCustomWeekHot3);
			session.setAttribute("goodsCustomSearch1", goodsCustomSearch1);	
			session.setAttribute("goodsCustomSearch2", goodsCustomSearch2);
			session.setAttribute("goodsCustomSearch3", goodsCustomSearch3);
			session.setAttribute("goodsCustomSearch4", goodsCustomSearch4);
		//	return "goods/brand";
		return "goods/search";
	}

	/**
	 * 商品浏览页
	 * 
	 * @param
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/brand")
	public String brandGood(HttpSession session) throws Exception {
		List<GoodsCustom> goodsCustoms = new ArrayList<GoodsCustom>();
		List<GoodsCustom> goodsCustomWeekHot4 = new ArrayList<GoodsCustom>();
		GoodsCustom goodsCustom1 = null;
		GoodsCustom goodsCustom2 = null;
		GoodsCustom goodsCustom3 = null;
		GoodsCustom goodsCustom4 = null;
		List<GoodsCustom> goodsCustomsRest = new ArrayList<GoodsCustom>();
		List<GoodsCustom> goodsCustomWeekHot3 = new ArrayList<GoodsCustom>();
		goodsCustoms = goodsService.selectAllGoodsInfo();

		int i = 0;
		for (GoodsCustom goodsCustom : goodsCustoms) {
			if (i < 4) {
				goodsCustomWeekHot4.add(goodsCustom);
			} else if (i < 5) {
				goodsCustom1 = goodsCustom;
			} else if (i < 6) {
				goodsCustom2 = goodsCustom;
			} else if (i < 7) {
				goodsCustom3 = goodsCustom;
			} else if (i < 8) {
				goodsCustom4 = goodsCustom;
			} else if (i < 13) {
				goodsCustomsRest.add(goodsCustom);
			} else if (i < 16) {
				goodsCustomWeekHot3.add(goodsCustom);
			} else {
				break;
			}
			i++;
		}

		session.setAttribute("goodsCustomsRest", goodsCustomsRest);
		session.setAttribute("goodsCustoms", goodsCustoms);
		session.setAttribute("goodsCustom1", goodsCustom1);
		session.setAttribute("goodsCustom2", goodsCustom2);
		session.setAttribute("goodsCustom3", goodsCustom3);
		session.setAttribute("goodsCustom4", goodsCustom4);
		session.setAttribute("goodsCustomWeekHot4", goodsCustomWeekHot4);
		session.setAttribute("goodsCustomWeekHot3", goodsCustomWeekHot3);
		return "goods/brand";
	}

	/**
	 * 商品单品销售页
	 * 
	 * @param
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/detailGoods")
	public String detailGoods(HttpSession session, HttpServletRequest request,
			@RequestParam(value = "id", required = true) Integer goodsId)
			throws Exception {
		GoodsCustom goodsCustom = goodsService
				.selectAllGoodsInfoByPrimaryKey(goodsId);
		System.out.println(goodsCustom);
		List<GoodsCustom> goodsCustoms = goodsService.selectAllGoodsInfo();
		List<GoodsCustom> goodsCustomsOnly3 = new ArrayList<GoodsCustom>();
		List<GoodsCustom> goodsCustomsWeekHot4 = new ArrayList<GoodsCustom>();
		List<GoodsCustom> goodsCustomsDay4 = new ArrayList<GoodsCustom>();
		int i = 0;
		for (GoodsCustom goodsCustom2 : goodsCustoms) {
			if (i < 3) {
				goodsCustomsOnly3.add(goodsCustom2);
			} else if (i < 7) {
				goodsCustomsWeekHot4.add(goodsCustom2);
			} else if (i < 11) {
				goodsCustomsDay4.add(goodsCustom2);
			} else {
				break;
			}
			i++;
		}
		session.setAttribute("goodsCustomsOnly3", goodsCustomsOnly3);
		session.setAttribute("goodsCustomsWeekHot4", goodsCustomsWeekHot4);
		session.setAttribute("goodsCustomsDay4", goodsCustomsDay4);
		request.setAttribute("goodsCustom", goodsCustom);
		return "goods/details";
	}

	/**
	 * 商品插入
	 * 
	 * @param goods
	 *            封装新增商品信息的实体
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/insertGoods")
	public String insertGoods(Goods goods, HttpSession httpSession,
			MultipartFile updateName, HttpServletRequest request)
			throws Exception {
		// 新增产品信息进入数据库
		goodsService.insertGoodsSelective(goods);

		// 上传新增商品额外信息进入数据库
		GoodsUpload goodsUpload = new GoodsUpload();
		goodsUpload.setGoodsId(goods.getGoodsId());
		goodsUpload.setUploadTime(new Date());
		/*
		 * upload_id//自增长 upload_location upload_name upload_type//图片类型
		 */

		// 上传头像
		String originalFilename = updateName.getOriginalFilename();
		File file;
		if (updateName != null && originalFilename != null
				&& originalFilename.length() > 0) {
			file = new File(request.getSession().getServletContext()
					.getRealPath("uploads")
					+ "\\"
					+ new SimpleDateFormat("yyyy\\MM\\dd").format(new Date())
					+ "\\" + originalFilename);
		} else {
			originalFilename = "default.jpg";
			// WebRoot-uploads-default.jpg
			file = new File(request.getSession().getServletContext()
					.getRealPath("uploads")
					+ "/" + originalFilename);
		}
		// 上传图片
		// 获取网站URL
		String path = request.getContextPath();

		// 存储图片的物理地址
		String uploadLoaction = path + "/uploads/"
				+ new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";

		// 服务器上存储图片的地址
		String realPath = request.getSession().getServletContext()
				.getRealPath("uploads")
				+ "\\"
				+ new SimpleDateFormat("yyyy\\MM\\dd").format(new Date())
				+ "\\";

		// 在服务器真实路径上创建文件夹
		File dir = new File(realPath);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		// 修改图片名称
		String uploadName = UUID.randomUUID()
				+ originalFilename.substring(originalFilename.lastIndexOf("."));

		// 上传图片类型
		String uploadType = "image/jpeg";
		goodsUpload.setUploadLocation(uploadLoaction);
		goodsUpload.setUploadName(uploadName);
		goodsUpload.setUploadType(uploadType);
		goodsUpload.setUploadTime(new Date());
		goodsUploadService.insertGoodsUpload(goodsUpload);

		// 新图片(存储的地方)
		File newFile = new File(realPath + uploadName);

		if (originalFilename == "default.jpg") {
			// 将内存中数据写入磁盘
			FileInputStream reader = new FileInputStream(file);
			FileOutputStream writer = new FileOutputStream(newFile);
			FileChannel in = reader.getChannel();
			FileChannel out = writer.getChannel();
			in.transferTo(0, in.size(), out);
			reader.close();
			writer.close();
		} else {
			updateName.transferTo(newFile);
			// 接收的文件转移到给定的目标文件newFile
		}
		// 想办法弹出一个新的并且界面提示成功
		// jsp中添加＜meta http-equiv="refresh" content="300; url=target.jsp"＞
		List<GoodsCustom> goodsSearch = goodsService.selectAllGoodsInfo();
		System.out.println(goodsSearch);
		httpSession.setAttribute("goodsSearch", goodsSearch);
		return "admin/index";

	}
}
